import React, { useEffect, useState } from 'react'
import { NavBar, Space, Toast, Form, Input, Button, Picker } from 'antd-mobile'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { reg } from '../../utils/validate'
import CaptchaBtn from '../../components/CaptchaBtn'
import { useLocalStorageState, useRequest } from 'ahooks'
import { captchaVerify, findUser, getToken } from '../../api/api'
import { ShowErrorMsg, ShowMsg } from '../../utils/message'
import { UserInterFace } from '../../utils/types'
import { useComment, useGoBackOrMine } from '../../hooks/common'


const LoginByPhone = () => {
  const router = useNavigate()
  const [form] = Form.useForm()
  const [query] = useSearchParams()
  const [phone, setPhone] = useState()
  const { GoBackOrMine } = useGoBackOrMine()


  // 登录成功后储存用户名
  const [AppPhone, setAppPhone] = useLocalStorageState<string | undefined>('AppPhone')

  // 登录成功后储存 token
  const [AppToken, setAppToken] = useLocalStorageState<string | undefined>('AppToken')

  useEffect(() => {
    if (query.get('phone')) {
      form.setFieldValue('phone', query.get('phone'))
    } else {
      form.setFieldValue('phone', AppPhone)
    }
    setPhone(form.getFieldValue('phone'))
  }, [])


  // 验证码登录 第一步 验证手机号是否已注册
  const checkPhone = useRequest(findUser, {
    manual: true, // 手动触发
    onSuccess: (res: any, params: any) => {
      if (res.result) {
        checkCaptcha.run(form.getFieldsValue())
      } else {
        ShowErrorMsg('手机号未注册')
      }
    }
  })

  // 验证码登录 第二步 验证验证码是否正确
  const checkCaptcha = useRequest(captchaVerify, {
    manual: true,
    onSuccess: (res: any, params: any) => {
      if (res.data) {
        getTokenApi.run({ phone: phone })
      } else {
        ShowErrorMsg('验证码错误')
      }
    }
  })

  // 验证码登录 第三步 登录成功
  const getTokenApi = useRequest(getToken, {
    manual: true,
    onSuccess: (res: any, params: any) => {
      if (res.code == 200) {
        ShowMsg("登录成功")
        // router('/main/mine')
        GoBackOrMine()
        setAppPhone(phone)
        setAppToken(res.token)
      }
    }
  })

  const onFinish = (value: UserInterFace) => {
    checkPhone.run({ phone: value.phone })
  }



  return (
    <div>
      <Form layout='horizontal' mode='card' form={form} onFinish={onFinish}>
        <Form.Header>请输入手机号，获取验证码以登录</Form.Header>
        <Form.Item
          label='手机号：'
          name='phone'
          rules={[
            { required: true, message: '手机号不能为空' },
            { pattern: reg.phone, message: '手机号格式不正确' }
          ]}
        >
          <Input placeholder='请输入手机号' clearable onChange={(phone: any) => setPhone(phone)} />
        </Form.Item>


        <CaptchaBtn phone={phone}></CaptchaBtn>

        <div>
          <Button color="success" className='mt20' block type="submit" >登 录</Button>
        </div>

        <div style={{ marginTop: '30px', display: 'flex', justifyContent: 'space-around' }}>
          <Button color='primary' fill='none' onClick={() => router('/reg')}>
            没有账号？去注册
          </Button>
          <Button color='primary' fill='none' style={{ marginLeft: '87px', fontSize: '14px', color: 'orange' }} onClick={() => router('/findpass')}>
            忘记密码
          </Button>
        </div>
      </Form>
    </div>
  )
}

export default LoginByPhone
